package com.example.license.client.filter;

import com.example.license.client.domain.LicenseVerify;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Order(1)
@Configuration
@WebFilter(filterName = "piceaFilter", urlPatterns = "/*" ,
        initParams = {@WebInitParam(name = "URL", value = "http://localhost:8080")})
public class PiceaFilter implements Filter {

    private static final Set<String> ALLOWED_PATHS =
            Collections.unmodifiableSet(new HashSet<>(Arrays.asList("/license/**")));


    private String url;

    /**
     * 可以初始化Filter在web.xml里面配置的初始化参数
     * filter对象只会创建一次，init方法也只会执行一次。
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.url = filterConfig.getInitParameter("URL");
        System.out.println("我是过滤器的初始化方法！URL=" + this.url +  "，生活开始.........");
    }

    /**
     * 主要的业务代码编写方法
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("我是过滤器的执行方法，客户端向Servlet发送的请求被我拦截到了");
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String path = request.getRequestURI().substring(request.getContextPath().length());

        // Spring 概念模型 : PathMatcher 路径匹配器
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        /*boolean allowedPath = false;
        for (String str:ALLOWED_PATHS){
            if(antPathMatcher.match(str, path)){
                allowedPath = true;
                break;
            }
        }*/

        if (! antPathMatcher.match("/license/**", path)) {
            LicenseVerify licenseVerify = new LicenseVerify();
            //校验证书是否有效
            boolean verifyResult = licenseVerify.verify();
            if(!verifyResult){
                response.addHeader("REDIRECT", "REDIRECT"); //告诉ajax这是重定向
                response.addHeader("CONTEXTPATH", request.getContextPath()+"/license/license-upload.html"); //重定向地址
                response.sendRedirect(request.getContextPath()+"/license/license-upload.html");
            }
        }

        // 进入 Filter 链（下一个Filter），最终web服务器就会调用web资源的service方法，即web资源就会被访问
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("我是过滤器的执行方法，Servlet向客户端发送的响应被我拦截到了");
    }

    /**
     * 在销毁Filter时自动调用。
     */
    @Override
    public void destroy() {
        System.out.println("我是过滤器的被销毁时调用的方法！，活不下去了................" );
    }
}
